package cn.wzy.service.impl;

import cn.wzy.constants.GiftConstants;
import cn.wzy.domain.Spu;
import cn.wzy.domain.SpuOnsaleDetail;
import cn.wzy.dto.GoodsSpuOnsaleDetailDocDto;
import cn.wzy.exception.ass.ValidUtils;
import cn.wzy.exception.code.ErrorCode;
import cn.wzy.mapper.SpuDetailMapper;
import cn.wzy.mapper.SpuMapper;
import cn.wzy.mapper.SpuOnsaleDetailMapper;
import cn.wzy.rocketmq.service.IRocketMqService;
import cn.wzy.service.ISpuService;
import cn.wzy.util.AjaxResult;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * spu表 服务实现类
 * </p>
 *
 * @author wzy
 * @since 2023-03-08
 */
@Service
public class SpuServiceImpl extends ServiceImpl<SpuMapper, Spu> implements ISpuService {


    @Autowired
    private SpuOnsaleDetailMapper detailMapper;
    @Autowired
    private IRocketMqService rocketMqService;
    @Autowired
    private SpuMapper spuMapper;
    /*
    * 上架
    * */
    @Override
    public AjaxResult onsale(List<Long> ids) throws GeneralSecurityException {
//      校验
        ValidUtils.isNotEmpty(ids, ErrorCode.ERROR_CODE_400);
//        判断是否上架过
        List<Spu> spuList = selectList(new EntityWrapper<Spu>()
                .eq("state", 1)
                .and()
                .in("id", ids));
        if (ids.size()!=spuList.size()){
            throw new GeneralSecurityException(ErrorCode.ERROR_CODE_TENANT_ONSALE_EXSIT.getMessage());
        }
//        修改数据库状态为上架
        List<Spu> collect = spuList.stream().map(x -> {
            x.setState(2);
            x.setOnsaleTime(new Date());
            return x;
        }).collect(Collectors.toList());
        updateAllColumnBatchById(collect);
//        添加上下架日志 @TODO

//        添加上下架详情信息,以便canal监控同步
        List<SpuOnsaleDetail> details = spuList.stream().map(y -> {
            SpuOnsaleDetail detail = new SpuOnsaleDetail();
            detail.setCover(y.getCover());
            detail.setMaxPrice(y.getHighPrice());
            detail.setMinPrice(y.getLowPrice());
            detail.setName(y.getGoodsName());
            detail.setTenantId(y.getTenantId());
            detail.setSpuId(y.getId());
            return detail;
        }).collect(Collectors.toList());
        for (SpuOnsaleDetail detail : details) {
            detailMapper.insert(detail);
        }
        //页面静态化 @TODO
        return AjaxResult.me();
    }

    /*
    * 下架
    * */
    @Override
    public AjaxResult offsale(List<Long> ids) throws GeneralSecurityException {
//        同上架一样
        //      校验
        ValidUtils.isNotEmpty(ids, ErrorCode.ERROR_CODE_400);
        //        判断是否上架
        List<Spu> spuList = selectList(new EntityWrapper<Spu>()
                .eq("state", 2)
                .and()
                .in("id", ids));
        if (ids.size()!=spuList.size()){
            throw new GeneralSecurityException(ErrorCode.ERROR_CODE_TENANT_OFFSALE_EXSIT.getMessage());
        }
        //        修改数据库状态为下架
        List<Spu> collect = spuList.stream().map(x -> {
            x.setState(3);
            x.setOnsaleTime(new Date());
            return x;
        }).collect(Collectors.toList());
        updateAllColumnBatchById(collect);
//        添加上下架日志 @TODO

        //        添加上下架详情信息,以便canal监控同步
        detailMapper.deleteBatchIds(ids);
        //页面静态化 @TODO
        return AjaxResult.me();
    }

    @Override
    public AjaxResult onsaleSendMsg(List<Long> ids) {
        try {
//        得到list
            List<Spu> spus = spuMapper.selectList(new EntityWrapper<Spu>().in("id", ids));
//            转成dto
            List<GoodsSpuOnsaleDetailDocDto> dtos = spus.stream().map(x -> {
                GoodsSpuOnsaleDetailDocDto dto = new GoodsSpuOnsaleDetailDocDto();
                dto.setId(x.getId());
                dto.setCover(x.getCover());
                dto.setName(x.getGoodsName());
                dto.setMax_price(x.getHighPrice());
                dto.setMin_price(x.getLowPrice());
                dto.setShop_id(x.getTenantId());
                dto.setShop_name(x.getTenantName());
                return dto;
            }).collect(Collectors.toList());
//            发送消息
            rocketMqService.sendTransMsg(GiftConstants.ONSALE_TX_PRODUCER_GROUP,
                    JSONArray.toJSONString(dtos) , GiftConstants.ONSALE_TX_PRODUCER_TOPIC);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false)
                    .setMessage(ErrorCode.ERROR_CODE_500.getMessage())
                    .setErrorCode(ErrorCode.ERROR_CODE_500.getCode());
        }
    }

    @Override
    public AjaxResult offsaleSendMsg(List<Long> ids) {
        try {
            //发送事务消息
            rocketMqService.sendTransMsg(GiftConstants.OFFSALE_TX_PRODUCER_GROUP,
                    JSONArray.toJSONString(ids) , GiftConstants.OFFSALE_TX_PRODUCER_TOPIC);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false)
                    .setMessage(ErrorCode.ERROR_CODE_500.getMessage())
                    .setErrorCode(ErrorCode.ERROR_CODE_500.getCode());
        }
    }
}
